package com.loujianwei.filter;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.louajianwei.constant.Constant;
import com.loujianwei.domain.User;
import com.loujianwei.permission.PermissionCheck;

// 使用的是 tomcat-servlet-api的过滤
public class LoginFilter implements Filter {
	
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		HttpServletResponse response = (HttpServletResponse)servletResponse;
		String uri = request.getRequestURI();
		// 不是登录请求相关时
		if(!uri.contains("sys/login_")){
			chain.doFilter(request, response); // 直接放行
//			// 获取session中保存的用户 session是服务器级别  客户端获取不了
//			User user = (User)request.getSession().getAttribute(Constant.USER);
//			if(user != null){ //说明已经登录过
//				//判断是否访问纳税服务系统
//				if(uri.contains("/nsfw/")){
//					//访问纳税服务子系统
//					//获取spring容器 代替了新建容器
//					WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
//					PermissionCheck permissionCheck = (PermissionCheck)applicationContext.getBean("permissionCheck");
//					// 校验不同权限，进入不同系统
//					if(permissionCheck.isAccessible(user, "nsfw")){
//						//说明有权限，放行
//						chain.doFilter(request, response);
//					} else {
//						//没有权限，重定向到 没有权限提示页面
//						response.sendRedirect(request.getContextPath() + "/sys/login_toNoPermissionUI.action");
//					}
//				} else {
//					//非访问纳税服务子系统，则直接放行
//					chain.doFilter(request, response);
//				}
//				
//			} else {
//				// 重定向到登录界面
//				response.sendRedirect(request.getContextPath() + "/sys/login_toLoginUI.action");
//			}
		} else {
			//登录请求；直接放行
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
